package com.haixiaoke.token;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.AppConstants;
import com.haixiaoke.saas.common.constant.HttpStatus;
import com.haixiaoke.saas.common.core.redis.RedisCache;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.GsonUtil;
import com.haixiaoke.saas.user.domain.UserConsumer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 */
@Component
public class FrontTokenComponent {

    @Resource
    private RedisCache redisCache;


    /**
     * 1分钟
     */
    private static final Long MINUTES = 60 * 1000L;

    /**
     * 1小时
     */
    private static final Long HOURS = 60 * MINUTES;

    /**
     * 1天
     */
    private static final Long DAYS = 24 * HOURS;


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            return redisCache.getCacheObject(userKey);
        }
        return null;
    }

    /**
     * 创建令牌
     *
     * @return 令牌
     */
    public String createToken(UserConsumer consumer) {

        String token = IdUtil.fastSimpleUUID();
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(consumer);
        loginUser.setToken(token);
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(System.currentTimeMillis()+ (DAYS*7));
        redisCache.setCacheObject(getTokenKey(token), loginUser, 7, TimeUnit.DAYS);
        return token;
    }

    /**
     * 验证令牌有效期，相差不足3分钟，自动刷新缓存
     *
     * @param loginUser LoginUserVo
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= 3 * MINUTES) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + 30 * DAYS);
        // 根据 uuid 将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, 30, TimeUnit.DAYS);
    }

    /**
     * 获取请求token
     *
     * @param request HttpServletRequest
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(AppConstants.HEADER_AUTHORIZATION_KEY);
        if (StrUtil.isNotEmpty(token) && token.startsWith(AppConstants.USER_TOKEN_REDIS_KEY_PREFIX)) {
            token = token.replace(AppConstants.USER_TOKEN_REDIS_KEY_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return AppConstants.USER_TOKEN_REDIS_KEY_PREFIX + uuid;
    }

    /**
     * 登出
     *
     * @param request HttpServletRequest
     */
    public void logout(HttpServletRequest request) {
        String token = getToken(request);
        delLoginUser(token);
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 获取当前登录用户id
     */
    public Long getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return null;
            // 抛不抛异常, 由 LocalUser 控制
            // throw new ServiceException("登录信息已过期，请重新登录！", HttpStatus.UNAUTHORIZED);
        }
        LoginUser loginUser = redisCache.getCacheObject(getTokenKey(token));
        if (ObjectUtil.isNull(loginUser)) {
            return null;
        }
        return loginUser.getUser().getUserId();
    }


    /**
     * 获取当前登录用户, 会抛出异常
     *
     */
    public LoginUser getLoginUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            // 抛不抛异常, 由 LocalUser 控制
            throw new ServiceException("登录信息已过期，请重新登录！", HttpStatus.UNAUTHORIZED);
        }
        return redisCache.getCacheObject(getTokenKey(token));
    }

    /**
     * 获取当前登录用户id, 会抛出异常
     */
    public Long getUserIdNotNull() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            // 抛不抛异常, 由 LocalUser 控制
            throw new ServiceException("登录信息已过期，请重新登录！", HttpStatus.UNAUTHORIZED);
        }
        LoginUser loginUser = redisCache.getCacheObject(getTokenKey(token));
        if (ObjectUtil.isNull(loginUser)) {
            // 抛不抛异常, 由 LocalUser 控制
            throw new ServiceException("登录信息已过期，请重新登录！", HttpStatus.UNAUTHORIZED);
        }
        return loginUser.getUser().getUserId();
    }


    public Boolean check(String token, HttpServletRequest request) {
        try {
            Boolean b = redisCache.hasKey(getTokenKey(token));
            if (b) {
                // 查询有效期, 如果有效期不足3分钟, 刷新有效期
                LoginUser loginUser = redisCache.getCacheObject(getTokenKey(token));
                verifyToken(loginUser);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
}
